<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img :src="avatar || avatarImg" alt="" />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input @change="updateImg" ref="inp" style="display:none" type="file" name="" id="">
        <el-button type="primary" icon="el-icon-plus" @click="$refs.inp.click()">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="!avatar" @click="uploadImg">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
import defaultImg from 'assets/images/avatar.jpg'
import { updateAvatar } from 'network/user'

export default {
  name: 'UserAvatar',
  data () {
    return {
      avatarImg: defaultImg,
      avatar: ''
    }
  },
  methods: {
    updateImg (e) {
      const file = e.target.files
      if (file.length === 0) {
        this.avatar = ''
        return
      }
      const fs = new FileReader()
      fs.readAsDataURL(file[0])
      fs.onload = (val) => {
        this.avatar = val.target.result
      }
    },
    async uploadImg () {
      const { data: res } = await updateAvatar({ avatar: this.avatar })
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.$store.dispatch('getUserInfo')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
}
</style>
